import type { IAuthLoginRes } from './types/login'
import { http } from '@/http/http'
import { useTokenStore } from '@/store/token'
import { toLoginPage } from '@/utils/toLoginPage'

/**
 * 获取微信登录凭证
 * @returns Promise 包含微信登录凭证(code)
 */
export function getWxCode() {
  return new Promise<UniApp.LoginRes>((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: res => resolve(res),
      fail: err => reject(new Error(err)),
    })
  })
}

/**
 * 微信登录
 * @param params 微信登录参数，包含code
 * @returns Promise 包含登录结果
 */
export function wxLogin(data: { code: string }) {
  return http.post<IAuthLoginRes>('/auth/wxLogin', data)
}

/**
 * 退出登录
 * @param showConfirm 是否显示确认提示，默认true
 * @returns Promise<void> 退出登录操作的Promise
 */
export function logout(showConfirm: boolean = true): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    const performLogout = async () => {
      try {
        const tokenStore = useTokenStore()
        await tokenStore.logout()
        toLoginPage({ mode: 'reLaunch' })
        resolve()
      }
      catch (error) {
        console.error('退出登录失败:', error)
        reject(error)
      }
    }

    if (showConfirm) {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            performLogout()
          }
          else {
            resolve() // 用户取消也视为成功完成操作
          }
        },
        fail: (err) => {
          console.error('显示退出确认失败:', err)
          reject(err)
        },
      })
    }
    else {
      performLogout()
    }
  })
}

/**
 * 刷新token
 */
export function refreshToken(token: string) {
  return http.post<IAuthLoginRes>('/auth/refreshToken', { token })
}
